package com.jna.unrar;

import com.jna.unrar.bean.RARHeaderData;
import com.jna.unrar.bean.RAROpenArchiveData;
import com.jna.unrar.cons.Constance;
import com.jna.unrar.jna.CLibrary;
import com.sun.jna.Pointer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.UnsupportedEncodingException;

public class UNRarUtil {
    private static final Logger logger = LoggerFactory.getLogger(UNRarUtil.class);

    /**
     * 解压rar文件。
     * @param rarFile
     * @param destDir
     * @return
     */
    public static int unRar(String rarFile,String destDir){
        File file = new File(rarFile);
        if(destDir==null){
            destDir = file.getParent();
        }
        logger.info("file check exists:{},canexecute:{},canRed:{},canWrite:{},filePath:{}",file.exists(),file.canExecute(),file.canRead(),file.canWrite(),file.getPath());
        RAROpenArchiveData rarOpenArchiveData = new RAROpenArchiveData();
        rarOpenArchiveData.ArcName = file.getPath();
        rarOpenArchiveData.OpenMode = Constance.RAR_OM_EXTRACT;
        rarOpenArchiveData.CmtBuf = "not";
        rarOpenArchiveData.CmtBufSize = 1024;
        logger.info("准备打开文档");
        Pointer pointer = CLibrary.INSTANCE.RAROpenArchive(rarOpenArchiveData);
        logger.info("ArcName" + rarOpenArchiveData.ArcName);
        logger.info("OpenMode" + rarOpenArchiveData.OpenMode);
        logger.info("OpenResult" + rarOpenArchiveData.OpenResult);
        logger.info("CmtBuf" + rarOpenArchiveData.CmtBuf);
        logger.info("CmtBufSize" + rarOpenArchiveData.CmtBufSize);
        logger.info("CmtSize" + rarOpenArchiveData.CmtSize);
        logger.info("CmtState" + rarOpenArchiveData.CmtState);
        logger.info("打开文档结束");
        logger.info("\n---------------------------\n");
        logger.info("解压文档开始");
        RARHeaderData rarHeaderDataEx = new RARHeaderData();
        int i2 ;
        String encoding = System.getProperty("sun.jnu.encoding");
        while ((i2=CLibrary.INSTANCE.RARReadHeader(pointer, rarHeaderDataEx))==0){
            try {
                logger.info("文件名称"+new String(rarHeaderDataEx.FileName,encoding));
            } catch (UnsupportedEncodingException e) {
                logger.error("",e);
            }
            i2 = CLibrary.INSTANCE.RARProcessFile(pointer, Constance.RAR_EXTRACT, destDir, null);
            if(i2!=0){
                break;
            }
        }
        logger.info("解压文档结束" + (i2 == 0 ? "SUCCESS" : i2));
        logger.info("\n---------------------------\n");
        logger.info("准备关闭");
        int i = CLibrary.INSTANCE.RARCloseArchive(pointer);
        logger.info("关闭" + (i == 0 ? "ERAR_SUCCESS" : i));
        return i;
    }
}
